package com.qianhong.crm.workbench.web.controller;

import com.qianhong.crm.commons.contanls.Contacts;
import com.qianhong.crm.commons.domain.ReturnObject;
import com.qianhong.crm.commons.utils.DateUtils;
import com.qianhong.crm.commons.utils.HSSCellUtils;
import com.qianhong.crm.commons.utils.UUIDUtils;
import com.qianhong.crm.settings.domain.User;
import com.qianhong.crm.settings.service.UserService;
import com.qianhong.crm.workbench.domain.Activity;
import com.qianhong.crm.workbench.domain.ActivityRemark;
import com.qianhong.crm.workbench.service.ActivityRemarkService;
import com.qianhong.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
public class ActivityController {
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String index(HttpServletRequest request) {
        List<User> userList = userService.queryAllUsers();
        request.setAttribute("userList", userList);
        return "workbench/activity/index";
    }

    @RequestMapping("/workbench/activity/saveCreatActivity.do")
    @ResponseBody
    public Object saveCreatActivity(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Contacts.SESSION_USER);  // "sessionUser"
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        activity.setCreateBy(user.getId());
        ReturnObject returnObject = new ReturnObject();
        try {
            int i = activityService.saveCreateActivity(activity);
            if (i > 0) {
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("插入成功");
            } else {
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("插入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnObject;
    }

    @RequestMapping("workbench/activity/queryActivityByConditionForPage.do")
    @ResponseBody
    public Object queryActivityByConditionForPage(String name, String owner, String startDate, String endDate,
                                                  int pageNo, int pageSize) {
        System.out.println("---------------->" + name + owner + startDate + endDate + pageNo + pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("owner", owner);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<Activity> activityList = activityService.queryActivityByConditionForPage(map);
        int totalRows = activityService.queryCountOfActivityByCondition(map);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("list", activityList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }

    @RequestMapping("workbench/activity/deleteActivityIds.do")
    @ResponseBody
    public Object deleteActivityIds(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            int ret = activityService.deleteActivityByIds(id);
            if (ret > 0) {
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("删除成功");
            } else {
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("删除失败");
        }
        return returnObject;
    }

    @RequestMapping("workbench/activity/selectActivityById.do")
    @ResponseBody
    public Object selectActivityById(String id) {
        Activity activity = activityService.queryActivityBYId(id);
        return activity;
    }

    @RequestMapping("workbench/activity/saveEditActivity.do")
    @ResponseBody
    public Object saveEditActivity(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Contacts.SESSION_USER);  // "sessionUser"
        activity.setEditTime(DateUtils.formatDateTime(new Date()));
        activity.setEditBy(user.getId());
        ReturnObject returnObject = new ReturnObject();
        try {
            int count = activityService.saveEditActivity(activity);
            if (count > 0) {
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("修改成功！");
            } else {
                System.out.println("-------------------------------------------------------------------");
                System.out.println(count);
                System.out.println("-------------------------------------------------------------------");
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("修改失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("修改失败！出现异常");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/fileDownLoad.do")
    @ResponseBody
    public void fileDownLoad(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        //浏览器接收到响应信息之后，默认情况下，直接在显示窗口中打开响应信息；即使打不开，也会调用应用程序打开；只有实在打不开，才会激活文件下载窗口。
        //可以设置响应头信息，使浏览器接收到响应信息之后，直接激活文件下载窗口，即使能打开也不打开
        response.addHeader("Content-Disposition", "attachment;filename=studentList.xls");
        InputStream is = new FileInputStream("D:/Program Files/Maven-project/out/studentList.xls");
//        OutputStream out1 = new FileOutputStream("");
        byte[] bytes = new byte[265];
        int readCount = 0;
        while ((readCount = is.read(bytes)) != -1) {
            System.out.println("上传成功！！");
            out.write(bytes, 0, readCount);
            System.out.println("上传成功！！");
        }
        is.close();
        out.flush();   // 写文件要刷新
    }

    @RequestMapping("/workbench/activity/exportAllActivity.do")
    @ResponseBody
    public void exportAllActivity(HttpServletResponse response) throws IOException {
        List<Activity> activityList = activityService.queryAllActivity();
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("市场活动列表");   // 创建页
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        if (activityList != null && activityList.size() > 0) {
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell = row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(2);
                cell.setCellValue(activity.getName());
                cell = row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(10);
                cell.setCellValue(activity.getEditBy());
            }
        }
       /* OutputStream os = new FileOutputStream("D:/Program Files/Maven-project/out/Activity.xls");
        wb.write(os);   //  效率低
        os.flush();
        os.close();
        wb.close();*/

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=studentList.xls");
        OutputStream out = response.getOutputStream();
     /*   InputStream is = new FileInputStream("D:/Program Files/Maven-project/out/Activity.xls");
        byte[] bytes = new byte[256];
        int readCount = 0;
        while((readCount = is.read(bytes)) != -1){
            out.write(bytes,0,readCount);
        }
        is.close();*/
        wb.write(out);
        wb.close();
        out.flush();
    }

    @RequestMapping("/workbench/activity/exportAllActivities.do")
    @ResponseBody
    public void exportAllActivities(String[] ids, HttpServletResponse response) throws IOException {
//        ids = new String[]{"d25cc1637a0648388b4a4ba74713c540", "1175e0cf01904e788c87b2017be862d9"};
        List<Activity> activityList = activityService.queryAllActivities(ids);
        HSSFWorkbook wb1 = new HSSFWorkbook();
        HSSFSheet sheet = wb1.createSheet("市场活动列表");   // 创建页
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        if (activityList != null && activityList.size() > 0) {
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell = row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(2);
                cell.setCellValue(activity.getName());
                cell = row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(10);
                cell.setCellValue(activity.getEditBy());
            }
        }

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=studentList.xls");
        OutputStream out = response.getOutputStream();
        wb1.write(out);
        wb1.close();
        out.flush();
    }

    @RequestMapping("/workbench/activity/importActivity.do")
    @ResponseBody
    public Object importActivity(MultipartFile activityFile, String userName, HttpSession session) {
        System.out.println("userName=" + userName);
        User user = (User) session.getAttribute(Contacts.SESSION_USER);
        ReturnObject returnObject = new ReturnObject();
        try {
            //把excel文件写到磁盘目录中
            /*String originalFilename = activityFile.getOriginalFilename();
            File file = new File("D:\\course\\18-CRM\\阶段资料\\serverDir\\", originalFilename);//路径必须手动创建好，文件如果不存在，会自动创建
            activityFile.transferTo(file);*/

            //解析excel文件，获取文件中的数据，并且封装成activityList
            //根据excel文件生成HSSFWorkbook对象，封装了excel文件的所有信息
            //InputStream is=new FileInputStream("D:\\course\\18-CRM\\阶段资料\\serverDir\\"+originalFilename);

            InputStream is = activityFile.getInputStream();   // 把文件放到流里面
            HSSFWorkbook wb = new HSSFWorkbook(is);
            //根据wb获取HSSFSheet对象，封装了一页的所有信息
            HSSFSheet sheet = wb.getSheetAt(0);//页的下标，下标从0开始，依次增加
            //根据sheet获取HSSFRow对象，封装了一行的所有信息
            HSSFRow row = null;
            HSSFCell cell = null;
            Activity activity = null;
            List<Activity> activityList = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {//sheet.getLastRowNum()：最后一行的下标
                row = sheet.getRow(i);//行的下标，下标从0开始，依次增加
                activity = new Activity();
                activity.setId(UUIDUtils.getUUID());
                activity.setOwner(user.getId());
                activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                activity.setCreateBy(user.getId());

                for (int j = 0; j < row.getLastCellNum(); j++) {//row.getLastCellNum():最后一列的下标+1
                    //根据row获取HSSFCell对象，封装了一列的所有信息
                    cell = row.getCell(j);//列的下标，下标从0开始，依次增加

                    //获取列中的数据
                    String cellValue = HSSCellUtils.getCellValueForStr(cell);
                    if (j == 0) {
                        activity.setName(cellValue);
                    } else if (j == 1) {
                        activity.setStartDate(cellValue);
                    } else if (j == 2) {
                        activity.setEndDate(cellValue);
                    } else if (j == 3) {
                        activity.setCost(cellValue);
                    } else if (j == 4) {
                        activity.setDescription(cellValue);
                    }
                }

                //每一行中所有列都封装完成之后，把activity保存到list中
                activityList.add(activity);
            }
           //调用service层方法，保存市场活动
        int ret=activityService.saveCreateActivityByList(activityList);

        returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_SUCCESS);
        returnObject.setRetData(ret);
    }catch (Exception e){
        e.printStackTrace();
        returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
        returnObject.setMessage("系统忙，请稍后重试....");
    }
        return returnObject;
    }
    /*@RequestMapping("/")
    @ResponseBody
    public String */

    @RequestMapping("/workbench/activity/detailActivity.do")
//    @ResponseBody   返回json数据  在返回路径的时候 不能能加
    public String detailActivity(String id ,HttpServletRequest request){
        Activity activity = activityService.queryActivityForDetailById(id);
        List<ActivityRemark> remarkList = activityRemarkService.queryActivityReMarkForDetailByActivityId(id);
        request.setAttribute("activity",activity);
        request.setAttribute("remarkList",remarkList);
//        System.out.println("slkdfjsdlk");
        return "workbench/activity/detail";
    }
}
